package com.hxkj.interceptor;

import com.hxkj.domain.enums.UserExceptionEnum;
import com.hxkj.domain.po.Token;
import com.hxkj.service.TokenService;
import com.platform.common.domain.exception.CustomException;
import com.platform.common.domain.result.ResultDataStruct;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * token认证拦截器
 *
 * @author chenwei
 * @version 1.0
 * @datetime 2017/12/10 17:47
 */
@Component
@Slf4j
public class AuthHandlerInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }

        Map<String, String> headersMap = getHeadersInfo(request);
        String accessToken = headersMap.get("accesstoken");

        if (StringUtils.isBlank(accessToken)) {
            throw new CustomException(UserExceptionEnum.TOKEN_NOT_EXIST);
        }

        ResultDataStruct<Token> resultDataStruct = tokenService.validate(accessToken);
        if (resultDataStruct.getCode() != 200)
            throw new CustomException(resultDataStruct.getMessage());

        Token token = resultDataStruct.getData();

        if (Objects.isNull(token)) {
            throw new CustomException(UserExceptionEnum.TOKEN_EXPIRES_CODE);
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) {
//        log.debug("这是认证拦截器 postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
//        log.debug("这是认证拦截器 afterCompletion");
    }

    /**
     * get request headers
     *
     * @param request
     * @return
     */
    private Map<String, String> getHeadersInfo(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = headerNames.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }

}
